package cn.summit.serialization.adapter;

import cn.summit.enums.EnumVO;
import cn.summit.serialization.SerialConstants;
import cn.summit.serialization.utils.SeriUtils;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 文件url自定获取
 *
 * @author summit
 * @since 2020/11/17 10:57
 */
@Slf4j
public class AttAdapter extends TypeAdapter<String> {


    @Override
    public void write(JsonWriter out, String value) throws IOException {
        if (value == null) {
            out.nullValue();
        } else {
            EnumVO enumVO = SeriUtils.getAttUrl(value);
            if (enumVO == null) {
                log.warn("文件url查询失败");
                out.value(value);
            } else {
                out.beginObject();
                out.name(SerialConstants.CODE).value(enumVO.getCode());
                out.name(SerialConstants.NAME).value(enumVO.getName());
                out.endObject();
            }
        }
    }

    @Override
    public String read(JsonReader in) throws IOException {
        String value = null;
        String code;

        JsonToken token = in.peek();

        switch (token) {
            case NULL:
                in.nextNull();
                return null;
            case STRING:
                return in.nextString();
            case BEGIN_OBJECT:
                in.beginObject();
                String name;
                while (in.hasNext()) {
                    name = in.nextName();
                    code = in.nextString();
                    if (SerialConstants.CODE.equals(name)) {
                        value = code;
                    }
                }
                in.endObject();
                return value;
            default:
                return null;
        }
    }
}

